package com.fudan.backend.service.impl;

import com.fudan.backend.dao.*;
import com.fudan.backend.exception.BaseException;
import com.fudan.backend.exception.RetCode;
import com.fudan.backend.pojo.Account;
import com.fudan.backend.pojo.Store;
import com.fudan.backend.pojo.StoreDeleteRequest;
import com.fudan.backend.pojo.statics.*;
import com.fudan.backend.service.AccountService;
import com.fudan.backend.service.StoreDeleteRequestService;
import com.fudan.backend.util.Snowflake;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class StoreDeleteRequestServiceImpl implements StoreDeleteRequestService {

    @Autowired
    StoreDeleteRequestDao storeDeleteRequestDao;

    @Autowired
    StoreDao storeDao;

    @Autowired
    UserDao userDao;

    @Autowired
    AccountDao accountDao;

    @Autowired
    AccountService accountService;
    @Autowired
    CommodityDao commodityDao;

    @Autowired
    CartDao cartDao;

    @Autowired
    OrderDao orderDao;

    @Autowired
    Snowflake snowflake;

    @Override
    public RetCode addStoreDeleteRequest(String storeId) {

        int count = storeDeleteRequestDao.selectStoreDeleteRequestCountByStoreName(storeId);
        if(count != 0){
            return RetCode.STORE_DELETE_REQUEST_HAS_EXISETED;
        }
        Date date = new Date();

        StoreDeleteRequest storeDeleteRequest = new StoreDeleteRequest();
        storeDeleteRequest.setStoreDeleteRequestId(((Long) snowflake.nextId()).toString());
        storeDeleteRequest.setInitiateTime(date);
        storeDeleteRequest.setStoreId(storeId);


        int orderCount = orderDao.selectOrderCountByStoreId(storeId);
        if(orderCount != 0){
            storeDeleteRequest.setProcessTime(date);
            storeDeleteRequest.setStatus(RequestStatus.NOT_APPROVED);
            storeDeleteRequest.setInfo("自动审核：有未处理的订单，目前不允许关闭商店");
        }else {
            storeDeleteRequest.setStatus(RequestStatus.APPLYING);
            storeDeleteRequest.setProcessTime(null);
        }

        int insertStoreDeleteRequest = storeDeleteRequestDao.insertStoreDeleteRequest(storeDeleteRequest);
        if(insertStoreDeleteRequest == 0){
            throw new BaseException(RetCode.STORE_DELETE_REQUEST_INSERT_FAILURE);
        }
        return RetCode.STORE_DELETE_REQUEST_SUCCESS;
    }

    @Override
    @Transactional
    public RetCode processStoreDeleteRequest(StoreDeleteRequest storeDeleteRequest) {
        Date date = new Date();

        storeDeleteRequest.setProcessTime(date);
        int updateStoreDeleteRequest = storeDeleteRequestDao.updateStoreDeleteRequest(storeDeleteRequest);
        if(updateStoreDeleteRequest == 0){
            throw new BaseException(RetCode.STORE_DELETE_REQUEST_UPDATE_FAILURE);
        }

        int status = storeDeleteRequest.getStatus();
        String storeId = storeDeleteRequest.getStoreId();


        if(status == RequestStatus.APPROVED){
            Store store = storeDao.selectStoreByStoreId(storeId);
            if(store == null){
                throw new BaseException(RetCode.STORE_NOT_FOUND);
            }
            store.setStatus(StoreStatus.CLOSED);
            int updateStore = storeDao.updateStore(store);
            if(updateStore == 0){
                throw new BaseException(RetCode.STORE_UPDATE_FAILURE);
            }

            String storeAccountId = store.getAccountId();
            Account storeAccount = accountDao.selectAccountByAccountId(storeAccountId);
            Double balance = storeAccount.getBalance();

            String userId = store.getUserId();
            String userAccountId = userDao.selectAccountIdByUserId(userId);
            //变更商品相关状态
            commodityDao.setCommodityStatusByStoreId(store.getStoreId(), CommodityStatus.REMOVED);
            //购物车状态
            cartDao.setStatusByStoreId(store.getStoreId(), CartItemStatus.Commodity_REMOVED);
            //注销商店账户
            accountDao.setStatusByAccountId(store.getAccountId(), AccountStatic.DRAW_DOWN);
            if(balance > 0.001){
                accountService.transfer(storeAccountId, userAccountId, balance, BillType.STORE_DELETE, "关店转账");
            }
        }
        return RetCode.STORE_DELETE_REQUEST_SUCCESS;
    }

    @Override
    public PageInfo<StoreDeleteRequest> getAllStoreDeleteRequest(int current, int pageSize) {
        PageHelper.startPage(current, pageSize);
        List<StoreDeleteRequest> storeDeleteRequests = storeDeleteRequestDao.selectAllStoreDeleteRequest();
        return new PageInfo<StoreDeleteRequest>(storeDeleteRequests, 5);
    }

    @Override
    public StoreDeleteRequest getStoreDeleteRequestByStoreDeleteRequestId(String storeDeleteRequestId) {
        StoreDeleteRequest storeDeleteRequest = storeDeleteRequestDao.selectStoreDeleteRequestByStoreDeleteRequestId(storeDeleteRequestId);
        if(storeDeleteRequest == null){
            throw new BaseException(RetCode.STORE_DELETE_REQUEST_NOT_FOUND);
        }
        return storeDeleteRequest;
    }

    @Override
    public PageInfo<StoreDeleteRequest> getAllStoreDeleteRequestByUserId(int current, int pageSize, String userId) {
        List<String> storeIds = storeDao.selectAllStoreIdByUserId(userId);
        if(storeIds.size() == 0){
            List<StoreDeleteRequest> list = new ArrayList<>();
            return new PageInfo<>(list);
        }
        PageHelper.startPage(current, pageSize);
        List<StoreDeleteRequest> storeDeleteRequests = storeDeleteRequestDao.selectStoreDeleteRequestByStoreIdList(storeIds);
        return new PageInfo<StoreDeleteRequest>(storeDeleteRequests, 5);
    }
}

